package com.prb.server.netty.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.prb.netty.AsyncResult;
import com.prb.netty.protocol.InvokeMsg;
import com.prb.netty.protocol.SmartCarProtocol;
import com.prb.server.service.UserService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

public class SimpleHandler extends ChannelInboundHandlerAdapter {

    // 用于获取客户端发送的信息  
    @Override  
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
            // 用于获取客户端发来的数据信息
            SmartCarProtocol body = (SmartCarProtocol) msg;

        InvokeMsg invokeMsg = JSONObject.parseObject(new String(body.getContent()) , InvokeMsg.class);

        //调用服务
        Object obj = invokeService(invokeMsg);

        AsyncResult asyncResult = new AsyncResult(invokeMsg.getInvokeId() , null  , obj);

        SmartCarProtocol response = new SmartCarProtocol(JSON.toJSONString(asyncResult).getBytes().length,
                JSON.toJSONString(asyncResult).getBytes());
        // 当服务端完成写操作后，关闭与客户端的连接  
        ctx.writeAndFlush(response);  

    }

    private Object invokeService(InvokeMsg invokeMsg) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class cls = invokeMsg.getClazz();
        Class[] params = invokeMsg.getParamTypes();
        List<Object> args = invokeMsg.getArgs();
        String methodName = invokeMsg.getMethodName();

        Method method = cls.getMethod(methodName, params);

        return method.invoke(new UserService() , args.get(0));
    }

    @Override  
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)  
            throws Exception {  
        // cause.printStackTrace();  
        ctx.close();  
    }  
} 